package com.thunder.h

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import com.thunder.kocho.devaloka.DevalokaLayout
import com.thunder.kocho.transition.ShrinkButton
import java.util.*

class ShrinkFragment : Fragment() {

    private lateinit var shrinkButton: ShrinkButton
    private lateinit var btnBack: Button
    private lateinit var btnNext: Button
    private lateinit var devalokaLayout: DevalokaLayout

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_shrink, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        shrinkButton = view.findViewById(R.id.shrinkButton)
        btnBack = view.findViewById(R.id.btnBack)
        btnNext = view.findViewById(R.id.btnNext)
        devalokaLayout = view.findViewById(R.id.devalokaLayout)
        shrinkButton.setOnPostListener(object : ShrinkButton.OnPostListener {
            override fun onPostClick() {
                val timer = Timer()
                val task: TimerTask = object : TimerTask() {
                    override fun run() {
                        val random = (0..1).random()
                        if (random == 0) {
                            shrinkButton.post {
                                shrinkButton.onWrong()
                            }
                        } else {
                            shrinkButton.post {
                                shrinkButton.onCorrect()
                            }
                        }
                    }
                }
                timer.schedule(task, 3000)
            }

            override fun onNewIntent() {
                Toast.makeText(context, "Going to a new activity!", Toast.LENGTH_SHORT).show()
                val intent = Intent(context, AnotherActivity::class.java)
                startActivity(intent)
                activity?.overridePendingTransition(R.anim.fade_in, R.anim.fade_out)
            }

            override fun onRegain() {
                Toast.makeText(context, "Login failed!", Toast.LENGTH_SHORT).show()
            }
        })

        btnBack.setOnClickListener {
            findNavController().navigate(R.id.circleFragment)
        }

        btnNext.setOnClickListener {
            findNavController().navigate(R.id.devalokaFragment)
        }

        devalokaLayout.postDelayed({
            devalokaLayout.onFocusChange(true)
        }, 3000)
    }
}